Page({
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
    redirect: ''
  },
  onLoad(options) {
    this.setData({
      redirect: options.redirectUrl
    })
  },
  //验证手机号码
  checkMobile() {
    const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    const valid = reg.test(this.data.mobile.trim())
    //用户提示
    if (!valid) wx.utils.toast('请填写正确的手机号码!')
    //返回结果
    return valid
  },
  //获取手机验证码
  async getCode() {
    if (!this.checkMobile()) return
    const res = await wx.http.get('/code', {
      mobile: this.data.mobile
    })

    this.setData({
      code: res.data.code,

    })
    wx.utils.toast('验证码发送成功')
    this.setData({
      countDownVisible: true
    })
  },
  //复制验证码
  copyCode() {
    wx.setClipboardData({
      data: this.data.code,
    })
  },
  countDownChange(ev) {
    // console.log(111);
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  //验证手机验证码
  verifyCode() {
    const reg = /^\d{6}$/
    const valid = reg.test(this.data.code.trim())
    if (!valid) wx.utils.toast('请输入正确的6位数验证码')
    return valid
  },
  // 登录功能
  async onSubmit() {
    //验证手机号和验证码
    if (!this.checkMobile()) return wx.utils.toast('请输入正确的手机号码')
    if (!this.verifyCode()) return wx.utils.toast('请输入正确的六位数验证码')
    //发请求
    const {
      code,
      mobile
    } = this.data
    const res = await wx.http.post('/login', {
      mobile,
      code
    })
    wx.utils.toast('登陆成功')
    //存token 从getApp
    getApp().setToken(res.data.token, res.data.refreshToken)
    // 存储完token后更新全局token（refreshtoken)  需要getApp()
    // console.log(app);
    //跳转页面
    const redirect = this.data.redirect || '/pages/my/index'
    //跳转到taber栏
    wx.reLaunch({
      url: redirect,
    })
  }
})